const sha1 = require('sha1')
const express = require('express')
const router = express.Router()

const UserModel = require('../models/users')
const checkNotLogin = require('../middlewares/check').checkNotLogin

// GET /signin 登录页
router.get('/', checkNotLogin, function(req, res, next) {
  res.render('login', {
    type: 'signin',
    articleType: null,
    originalUrl: null
  })
})

// POST /signin 用户登录
router.post('/', checkNotLogin, function(req, res, next) {
  const from = req.query.from || '/'
  const name = req.fields.name
  const password = req.fields.password
  UserModel.getUserByName(name)
    .then(function (user) {
      if (!user) {
        req.flash('error', '用户不存在')
        return res.redirect('back')
      }
      // 检查密码是否匹配
      if (sha1(password) !== user.password) {
        req.flash('error', '密码错误')
        return res.redirect('back')
      }
      req.flash('success', '登录成功')
      // 用户信息写入 session
      delete user.password
      if (user.name === '838186163@qq.com') {
        user.privilege = 1;
      }
      req.session.user = user;
      // 跳转到上一页
      return res.redirect(from)
    })
    .catch(next)
})

module.exports = router